package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.dtos.HistorySearchDto;
import com.heima.search.pojo.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {


    @Autowired
    MongoTemplate mongoTemplate;


    /**
     * 删除历史记录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {

        //1 得到登录用户
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || user.getId() == 0) {
            return ResponseResult.okResult();
        }

        //2 执行删除
        mongoTemplate.remove(Query.query(Criteria.where("_id").is(dto.getId())), ApUserSearch.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询用户搜索历史记录
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {

        //1 得到登录用户
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || user.getId() == 0) {
            return ResponseResult.okResult();
        }

        //2 执行查询历史记录 根据时间倒序
        List<ApUserSearch> userSearchList = mongoTemplate.find(Query.query(Criteria
                        .where("entryId").is(user.getId()))
                        .with(Sort.by(Sort.Direction.DESC,"createdTime"))
                        .limit(10),
                ApUserSearch.class);


        //3 返回结果
        return ResponseResult.okResult(userSearchList);
    }

    /**
     * 保存用户搜索历史记录
     * @param keyword
     * @param userId
     */
    @Override
    @Async // 异步保存
    public void insert(String keyword, Integer userId) {

        //1.查询当前用户的搜索关键词
        ApUserSearch userSearch= mongoTemplate.findOne(Query.query(Criteria
                        .where("entryId").is(userId)
                        .and("keyword").is(keyword)
                ),
                ApUserSearch.class);

        //2.存在 更新创建时间
        if (userSearch != null) {
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
            return;
        }

        //3 不存在，判断当前历史记录总数量是否超过10
        List<ApUserSearch> userSearchList = mongoTemplate.find(Query.query(Criteria
                        .where("entryId").is(userId))
                        .with(Sort.by(Sort.Direction.DESC,"createdTime")),
                ApUserSearch.class);

        userSearch = new ApUserSearch();
        userSearch.setEntryId(userId);
        userSearch.setKeyword(keyword);
        userSearch.setCreatedTime(new Date());

        //3.1 未超过 直接新增
        if (userSearchList == null || userSearchList.size() < 10) {
            mongoTemplate.save(userSearch);
            log.info("新增关键词成功");
        } else {
            //3.2 超过 先删最后一条 保存当前记录
            ApUserSearch lastUserSearch = userSearchList.get(userSearchList.size() - 1);

            mongoTemplate.findAndReplace(
                    Query.query(Criteria.where("_id").is(lastUserSearch.getId())),
                    userSearch);
            log.info("替换关键词成功");
        }
    }
}
